import axios from 'axios';
import qs from "qs";
import { MessageBox, Message } from 'element-ui'

axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';



export function getApiBase() {
    return "https://blog.xiaozhengkeji.com:233";
}

const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    baseURL: 'https://blog.xiaozhengkeji.com:233',
    timeout: 5000
});

service.interceptors.request.use(

    config => {
        const CToken = localStorage.getItem('ms_token');
        if (CToken != null) {
            config.headers['token'] = CToken;
        }
        if (config.method === 'post') {
            config.data = qs.stringify(config.data);
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        const res = response.data
        console.log('res -> ' + JSON.stringify(res)) // 用于调试
        if (res.code !== 20000) {
            Message({
                message: res.msg || 'Error',
                type: 'error',
                duration: 5 * 1000
            })
            //return Promise.reject(new Error(res.msg || 'Error'))
            return null;
        } else {
            return res;
        }
    },
    error => {
        console.log('err' + error) // 用于调试
        switch (error.response.status) {
            case 400:
                resError("请求错误!");
                break;
            case 401:
                resError("账户错误或者密码错误!");
                break;
            default:
                resError(error);
        }
        return Promise.reject();
    }
);
export function resError(msg) {
    Message({
        message: msg,
        type: 'error',
        duration: 5 * 1000
    })
}

export default service;
